package com.heer.gymnasium.module.my.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.module.evaluate.beans.EvaTagBean;
import com.heer.gymnasium.module.evaluate.beans.UserTagResponseBean;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.module.my.beans.UserBean;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.StringUtils;
import com.heer.gymnasium.widget.GlideCenterRoundImage;
import com.heer.gymnasium.widget.GlideRoundImage;
import com.heer.imagepick.DensityUtils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by yan
 * on 2018/2/13
 * 我的标签界面
 */

public class MyLabelActivity extends BaseActivity implements TagFlowLayout.OnTagClickListener {
    private static final int RES_ID_LAYOUT = R.layout.layout_label;
    private static final int RES_ID_FLOWLAYOUT = R.id.layout_label_flowlayout;
    private static final int RES_ID_CROP_LL = R.id.layout_label_corp_panel_ll;
    private static final int RES_ID_GIVE_OWN = R.id.layout_label_give_own_tfl;
    private static final int RES_ID_NAME = R.id.layout_label_name_tv;
    private static final int RES_ID_MORE = R.id.layout_label_more_iv;
    private static final int RES_ID_COMPLETE = R.id.layout_label_complete_tv;
    private static final int RES_ID_HEAD = R.id.layout_label_head_iv;
    private static final int RES_ID_TEL = R.id.layout_label_member_tel_tv;
    private static final int RES_ID_GIVE_OWN_LL = R.id.layout_label_self_panel_ll;

    @BindView(RES_ID_FLOWLAYOUT)
    TagFlowLayout myTagFlowLayout;
    @BindView(RES_ID_GIVE_OWN)
    TagFlowLayout giveOwnFlowLayout;
    @BindView(RES_ID_HEAD)
    ImageView headImageView;
    @BindView(RES_ID_NAME)
    TextView nameTextView;
    @BindView(RES_ID_TEL)
    TextView telTextView;
    @BindView(RES_ID_COMPLETE)
    TextView completeTextView;
    @BindView(RES_ID_MORE)
    ImageView moreImageView;
    @BindView(RES_ID_CROP_LL)
    LinearLayout cropLinearlayout;
    @BindView(RES_ID_GIVE_OWN_LL)
    LinearLayout giveOwnLinearlayout;

    private List<EvaTagBean> myTagList, giveOwnList;
    private TagAdapter<EvaTagBean> myTagAdapter, giveOwnAdapter;

    private Activity $this;
    private boolean isDown = true;

    private String mid, corpsId;//成员id
    private boolean isMemberPage = false;
    private int d5, d10;

    @Override
    protected void init() {
        super.init();
        setContentView(RES_ID_LAYOUT);
        $this = this;
        mid = getIntent().getStringExtra(EXTRA_ID);
        isMemberPage = !TextUtils.isEmpty(mid);
        if (isMemberPage) {
            corpsId = getIntent().getStringExtra(EXTRA_DATA);
        }
        d5 = DensityUtils.dip2px($this, 5);
        d10 = d5 * 2;
        myTagList = new ArrayList<>();
        giveOwnList = new ArrayList<>();
        myTagAdapter = new TagAdapter<EvaTagBean>(myTagList) {
            @Override
            public View getView(FlowLayout parent, int position, EvaTagBean evaTagBean) {
                TextView textView = new TextView($this);
                textView.setText(evaTagBean.getName());
                if (evaTagBean.isOwn()) {
                    textView.setTextColor(getResources().getColor(R.color.coloryellow));
                    textView.setBackgroundResource(R.drawable.yellow_border);
                } else {
                    textView.setTextColor(getResources().getColor(R.color.white));
                    textView.setBackgroundResource(R.drawable.yellow_button_small);
                }
                return textView;
            }
        };

        giveOwnAdapter = new TagAdapter<EvaTagBean>(giveOwnList) {
            @Override
            public View getView(FlowLayout parent, final int position, final EvaTagBean evaTagBean) {
                TextView textView = new TextView($this);
                textView.setText(evaTagBean.getName());
                if (evaTagBean.isSelect()) {
                    textView.setTextColor(getResources().getColor(R.color.white));
                    textView.setBackgroundResource(R.drawable.yellow_button_small);
                } else {
                    textView.setTextColor(getResources().getColor(R.color.font_gray));
                    textView.setBackgroundResource(R.drawable.white_corner_bg);
                }
                return textView;
            }
        };

    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.startMainActivity(this);
        if (isMemberPage) {
            titleUtils.setTitleText("成员信息");
            giveOwnLinearlayout.setVisibility(View.GONE);
            completeTextView.setVisibility(View.GONE);
        } else {
            cropLinearlayout.setVisibility(View.GONE);
            titleUtils.setTitleText("我的标签");
            giveOwnFlowLayout.setAdapter(giveOwnAdapter);
            giveOwnFlowLayout.setOnTagClickListener(this);
            UserBean bean = (UserBean) getIntent().getSerializableExtra(EXTRA_DATA);
            ImageUtil.loadUrl($this, bean.getAvatar(), R.drawable.ic_default_head, headImageView);
            nameTextView.setText(bean.getNickname());
        }
        myTagFlowLayout.setAdapter(myTagAdapter);

    }

    @Override
    protected void loadData() {
        super.loadData();
        if (isMemberPage) {
            getMemberInfo(mid, corpsId);
        } else {
            getUserTagList();
            getTagList("2");

        }
    }

    @OnClick(RES_ID_COMPLETE)
    public void completeOnClick(View view) {
        if (!isMemberPage) {
            setuserInfo();
        }
    }

//    @OnClick(RES_ID_MORE)
//    public void moreOnClick(View view) {
//        if (isDown) {
//            isDown = false;
//            giveOwnFlowLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//            moreImageView.setBackgroundResource(R.drawable.ic_tow_up);
//        } else {
//            isDown = true;
//            giveOwnFlowLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DensityUtils.dip2px($this, 50)));
//            moreImageView.setBackgroundResource(R.drawable.ic_tow_down);
//        }
//    }

    public static void startActivity(Context context, UserBean bean) {
        Intent intent = new Intent(context, MyLabelActivity.class);
        intent.putExtra(EXTRA_DATA, bean);
        context.startActivity(intent);
    }

    /**
     * 成员详情
     *
     * @param context
     * @param memberId
     * @param cropsId  战队id
     * @Description 从战队详情下成员列表进入
     */
    public static void startActivity(Context context, String memberId, String cropsId) {
        if (TextUtils.isEmpty(memberId) || TextUtils.isEmpty(cropsId)) {
            ToastUtil.show(context, "成员信息异常");
            return;
        }
        Intent intent = new Intent(context, MyLabelActivity.class);
        intent.putExtra(EXTRA_ID, memberId);
        intent.putExtra(EXTRA_DATA, cropsId);
        context.startActivity(intent);
    }

    //获取标签 0:教练，1：场馆,2:用户,3:战队
    private void getTagList(String type) {
        mAppHelper.apiService().getTagList(type).enqueue(new BaseCallback<ApiResponse<List<EvaTagBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<EvaTagBean>>> call, Response<ApiResponse<List<EvaTagBean>>> response) {
                giveOwnList.clear();
                giveOwnList.addAll(response.body().getData());
                if (giveOwnList.size() > 0) {
                    giveOwnList.get(0).setSelect(true);
                }
                giveOwnAdapter.notifyDataChanged();
            }
        });
    }

    //获取我的标签
    private void getUserTagList() {
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getUserTagList(signHelper.getToken()).enqueue(new BaseCallback<ApiResponse<UserTagResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<UserTagResponseBean>> call, Response<ApiResponse<UserTagResponseBean>> response) {
                myTagList.clear();
                fillData(response.body().getData());
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    //获取成员信息
    private void getMemberInfo(String member_id, String corps_id) {
        mAppHelper.apiService().getMemberInfo(member_id, corps_id).enqueue(new BaseCallback<ApiResponse<UserTagResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<UserTagResponseBean>> call, Response<ApiResponse<UserTagResponseBean>> response) {
                fillData(response.body().getData());
            }
        });
    }

    private void fillData(UserTagResponseBean responseBean) {
        myTagList.clear();
        if (isMemberPage) {
            nameTextView.setText(responseBean.getNickname());
            Glide.with($this).load(responseBean.getAvatar()).into(headImageView);
            if (!TextUtils.isEmpty(responseBean.getUsername())) {
                telTextView.setText(responseBean.getUsername());
            } else {
                telTextView.setText("仅同战队可见");
            }
        } else {

        }

        List<String> tag_me = responseBean.getTag_me();
        if (tag_me != null) {
            for (int i = 0; i < tag_me.size(); i++) {
                EvaTagBean bean = new EvaTagBean();
                bean.setName(tag_me.get(i));
                bean.setOwn(true);
                myTagList.add(bean);
            }
        }

        List<String> tag_other = responseBean.getTag_other();
        if (tag_other != null) {
            for (int i = 0; i < tag_other.size(); i++) {
                EvaTagBean bean = new EvaTagBean();
                bean.setName(tag_other.get(i));
                bean.setOwn(false);
                myTagList.add(bean);
            }
        }

        myTagAdapter.notifyDataChanged();
    }

    //设置用户信息
    private void setuserInfo() {
        String birthday = "", weight = "", height = "", nickname = "", sex = "";
        StringBuffer tag_me = new StringBuffer();

        for (int i = 0; i < giveOwnList.size(); i++) {
            if (giveOwnList.get(i).isSelect()) {
                tag_me.append(giveOwnList.get(i).getId() + ",");
            }
        }

        if (TextUtils.isEmpty(tag_me.toString())) {
            ToastUtil.show($this, "暂无选择评价标签");
            return;
        } else {
            tag_me.delete(tag_me.length() - 1, tag_me.length());
        }

        mAppHelper.apiService().setUserInfo(birthday, weight, height, nickname, sex, tag_me.toString()).enqueue(new BaseCallback<ApiResponse<String>>() {

            @Override
            public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                ToastUtil.show($this, "保存成功");
                finish();
            }
        });
    }

    @Override
    public boolean onTagClick(View view, int position, FlowLayout parent) {
        if (giveOwnList.get(position).isSelect()) {
            giveOwnList.get(position).setSelect(false);
        } else {
            giveOwnList.get(position).setSelect(true);
        }
        giveOwnAdapter.notifyDataChanged();
        return false;
    }
}
